import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd';
import { Question } from '../../entity/Question';
import { Router } from '@angular/router';
import { User } from '../../entity/User';

@Component({
  selector: 'app-question-create',
  templateUrl: './question-create.component.html',
  styleUrls: ['./question-create.component.css']
})
export class QuestionCreateComponent implements OnInit {
  title: string;
  question: string;
  user: User;

  constructor(private http: HttpClient
    , private userService: UserService
    , private router: Router
    , private message: NzMessageService) { }

  ngOnInit() {
    this.user = this.userService.getUser();
  }

  submit() {
    if (this.title == null || this.title == '') {
      this.message.error('问题不能为空！');
      return;
    }
    const postItem = new Question();
    postItem.questionUser = this.user.name;
    postItem.title = this.title;
    postItem.question = this.question;
    this.http
      .post(`/api/Questions/insert`, JSON.stringify(postItem), {
        headers: new HttpHeaders({
          'Content-type': 'application/json'
        })
      })
      .subscribe(response => {
        if (!response as boolean) {
          this.message.error('提交问题失败');
        } else {
          this.router.navigate(['/content/question']);
        }
      });
  }
}
